import {defineStore} from "pinia";
import {ref} from "vue";
import {getRolesDic} from "@/api/role";

import type {RoleDictionary} from "@/api/role/type.ts";

export const useRoleStore = defineStore('useRoleStore', () => {

  const roleList = ref<RoleDictionary[]>([]);

  /**
   * 获取字典数据
   */
  async function fetchDictionaries() {
    try {
      const res = await getRolesDic();
      if (res.code === "M000") {
        roleList.value = res.data;
      }
    } catch (e) {
      console.error("获取角色字典失败", e);
    }
  }


  /**
   * 根据角色编码获取角色名称
   * @param code
   */
  function getRoleName(code: string): string {
    return getRoleByCode(code).desc!;
  }

  /**
   * 获取角色优先权
   * @param code
   */
  function getRoleOrder(code: string): number {
    return getRoleByCode(code).order;
  }

  /**
   * 根据角色编码获取角色
   * @param code
   */
  function getRoleByCode(code: string) {
    const role = roleList.value.find(item => item.code === code)
    if (!role) {
      throw new Error("获取角色-->未知角色类型")
    }
    return role;
  }

  return {
    roleList,
    fetchDictionaries,
    getRoleName,
    getRoleOrder
  }
})
